package cn.yh.register.order.api;

import cn.yh.register.common.result.Result;
import cn.yh.register.enums.PaymentTypeEnum;
import cn.yh.register.order.service.PaymentService;
import cn.yh.register.order.service.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api(tags = "微信支付")
@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {


    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation("获取微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public Result<Map<String, Object>> createNative(@PathVariable Long orderId) throws Exception {
        Map<String, Object> map = weiXinService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation("第三方查看微信支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result<?> queryPayStatus(@PathVariable("orderId") Long orderId) throws Exception {
        //1.调service
        Map<String, String> resultMap = weiXinService.queryPayStatus(orderId,PaymentTypeEnum.WEIXIN.getComment());
        //2.查看是否支付成功
        if (resultMap == null) {
            return Result.fail().message("支付出错");
        }
        if (resultMap.get("return_code").equals("SUCCESS")
                && resultMap.get("result_code").equals("SUCCESS")
                && resultMap.get("trade_state").equals("SUCCESS")) {
            // 支付成功 更新支付记录，更新订单状态，调医院系统更新订单状态
            paymentService.paySuccess(resultMap.get("out_trade_no"),
                    PaymentTypeEnum.WEIXIN.getStatus(),
                    resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}